package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.WebUserCardRechargeMapper;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 充值服务Service业务层处理
 * 
 * @author wsliupan@126.com
 * @date 2021-06-27
 */
@Service
public class WebUserCardRechargeServiceImpl extends ServiceImpl<WebUserCardRechargeMapper, WebUserCardRecharge> implements IWebUserCardRechargeService
{
    @Autowired
    private WebUserCardRechargeMapper webUserCardRechargeMapper;

    /**
     * 查询充值服务
     * 
     * @param id 充值服务ID
     * @return 充值服务
     */
    @Override
    public WebUserCardRecharge selectWebUserCardRechargeById(Long id)
    {
        return webUserCardRechargeMapper.selectWebUserCardRechargeById(id);
    }

    /**
     * 查询充值服务列表
     * 
     * @param webUserCardRecharge 充值服务
     * @return 充值服务
     */
    @Override
    @DataScope(deptAlias = "t1")
    public List<WebUserCardRecharge> selectWebUserCardRechargeList(WebUserCardRecharge webUserCardRecharge)
    {
        return webUserCardRechargeMapper.selectWebUserCardRechargeList(webUserCardRecharge);
    }

    /**
     * 新增充值服务
     * 
     * @param webUserCardRecharge 充值服务
     * @return 结果
     */
    @Override
    @Transactional
    public int insertWebUserCardRecharge(WebUserCardRecharge webUserCardRecharge)
    {
        webUserCardRecharge.setCreateTime(DateUtils.getNowDate());
        webUserCardRechargeMapper.insert(webUserCardRecharge);

        WebUserCardRechargeLog userCardTimeLog = new WebUserCardRechargeLog();
        userCardTimeLog.setUserId(webUserCardRecharge.getUserId());
        userCardTimeLog.setTimeId(webUserCardRecharge.getId());
        userCardTimeLog.setMoney(webUserCardRecharge.getMoney());
        userCardTimeLog.setDeptId(webUserCardRecharge.getDeptId());
        userCardTimeLog.setResidue(webUserCardRecharge.getMoney());
        iWebUserCardRechargeLogService.save(userCardTimeLog);
        return 1;
    }

    /**
     * 修改充值服务
     * 
     * @param webUserCardRecharge 充值服务
     * @return 结果
     */
    @Override
    public boolean updateWebUserCardRecharge(WebUserCardRecharge webUserCardRecharge)
    {
        //webUserCardRecharge.setUpdateTime(DateUtils.getNowDate());
        //return webUserCardRechargeMapper.updateWebUserCardRecharge(webUserCardRecharge);
        return this.saveOrUpdate(webUserCardRecharge);
    }

    /**
     * 删除充值服务对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public boolean deleteWebUserCardRechargeByIds(String ids)
    {
        //return webUserCardRechargeMapper.deleteWebUserCardRechargeByIds(Convert.toStrArray(ids));
        return this.removeByIds(Arrays.asList(Convert.toStrArray(ids)));
    }

    /**
     * 删除充值服务信息
     * 
     * @param id 充值服务ID
     * @return 结果
     */
    @Override
    public boolean deleteWebUserCardRechargeById(Long id)
    {
        //return webUserCardRechargeMapper.deleteWebUserCardRechargeById(id);
        return this.removeById(id);
    }

    /**
     * 消费
     * @param webUserCardRecharge
     * @return
     */
    @Transactional
    public boolean consumption(WebUserCardRecharge webUserCardRecharge){
        WebUserCardRecharge data=  this.getById(webUserCardRecharge.getId());
        if(data == null){
            throw new BusinessException("数据不存在");
        }
        BigDecimal money = data.getMoney().subtract(webUserCardRecharge.getMoney());
        if(money.doubleValue() < 0){
            throw new BusinessException("卡余额不足");
        }
        data.setMoney(money);
        this.saveOrUpdate(data);

        WebUserCardRechargeLog userCardTimeLog = new WebUserCardRechargeLog();
        userCardTimeLog.setUserId(data.getUserId());
        userCardTimeLog.setTimeId(data.getId());
        userCardTimeLog.setMoney(webUserCardRecharge.getMoney().negate());
        userCardTimeLog.setDeptId(data.getDeptId());
        userCardTimeLog.setCommend((String)webUserCardRecharge.getParams().get("commend"));
        userCardTimeLog.setResidue(data.getMoney());
        userCardTimeLog.setNumber(Integer.valueOf(webUserCardRecharge.getParams().get("number")+""));
        userCardTimeLog.setProductName(webUserCardRecharge.getParams().get("selectProductName")+"");
        userCardTimeLog.setProductId(Integer.valueOf(webUserCardRecharge.getParams().get("selectProductId")+""));
        iWebUserCardRechargeLogService.save(userCardTimeLog);

        //扣减库存
        if(userCardTimeLog.getProductId() != null){
            WebDeptProduct deptproduct = iWebDeptProductService.getById(userCardTimeLog.getProductId());
            if(deptproduct != null){
                long number = new BigDecimal( deptproduct.getStock()+"").subtract(new BigDecimal(userCardTimeLog.getNumber()+"")).longValue();
                if(number < 0){
                    throw new BusinessException("库存不足");
                }
                iWebDeptProductService.update(new UpdateWrapper<WebDeptProduct>()
                        .eq("id",deptproduct.getId())
                        .set("stock",number)
                );
            }

            SysDept sysDept = iSysDeptService.selectDeptById(deptproduct.getDeptId());
            WebUser webUser = iWebUserService.getById(data.getUserId());
            WebDeptProductLog productLog = new WebDeptProductLog();
            productLog.setDeptId(deptproduct.getDeptId());
            productLog.setDeptName(sysDept.getDeptName());
            productLog.setProductId(deptproduct.getId());
            productLog.setProductName(deptproduct.getName());
            productLog.setWebUserId(data.getUserId());
            productLog.setWebUserName(webUser.getNickname()+"-"+webUser.getRealname());
            productLog.setNumber("-"+userCardTimeLog.getNumber()+"");
            productLog.setComment("充值卡消费产品出库");
            iWebDeptProductLogService.save(productLog);

        }

        return true;
    }

    /**
     * 充值
     * @param webUserCardRecharge
     * @return
     */
    @Transactional
    public boolean chongzhi(WebUserCardRecharge webUserCardRecharge){
        WebUserCardRecharge data = this.getById(webUserCardRecharge.getId());
        if(data == null){
            throw new BusinessException("未获取到充值卡数据");
        }
        if(webUserCardRecharge.getMoney()== null){
            throw new BusinessException("未获取到充值金额");
        }
        data.setMoney(data.getMoney().add(webUserCardRecharge.getMoney()));
        data.setCountMoney(data.getCountMoney().add(webUserCardRecharge.getMoney()));
        this.saveOrUpdate(data);

        WebUserCardRechargeLog userCardTimeLog = new WebUserCardRechargeLog();
        userCardTimeLog.setUserId(data.getUserId());
        userCardTimeLog.setTimeId(data.getId());
        userCardTimeLog.setMoney(webUserCardRecharge.getMoney());
        userCardTimeLog.setDeptId(data.getDeptId());
        userCardTimeLog.setResidue(data.getMoney());
        iWebUserCardRechargeLogService.save(userCardTimeLog);

        return true;
    }
    /**
     * 转换次卡
     * @param webUserCardRecharge
     * @param userCardTime
     * @return
     */
    @Transactional
    public boolean transitionSave(WebUserCardRecharge webUserCardRecharge, WebUserCardTime userCardTime){
        WebUserCardRecharge data = this.getById(webUserCardRecharge.getId());
        data.setStatus("N");
        this.saveOrUpdate(data);
        userCardTime.setUserId(data.getUserId());
        userCardTime.setTimes(userCardTime.getCountTimes());
        iWebUserCardTimeService.save(userCardTime);

        WebUserCardRechargeTransition cardRechargeTransition = new WebUserCardRechargeTransition();
        cardRechargeTransition.setDeptId(data.getDeptId());
        cardRechargeTransition.setTimeId(userCardTime.getId());
        cardRechargeTransition.setRechargeId(data.getId());
        cardRechargeTransition.setUserId(data.getUserId());
        cardRechargeTransition.setMoney(data.getMoney());
        cardRechargeTransition.setTotalMoney(data.getCountMoney());
        cardRechargeTransition.setTimeCount(new BigDecimal(userCardTime.getTimes()));
        iWebUserCardRechargeTransitionService.save(cardRechargeTransition);
        return true;
    }
    /**
     * 统计
     * @param webUserCardRecharge
     * @return
     */
    @DataScope(deptAlias = "t1")
    public List<Map> selectIndexData(WebUserCardRecharge webUserCardRecharge){
        return this.webUserCardRechargeMapper.selectIndexData(webUserCardRecharge);
    }

    /**
     * 查询用户的总次数（小程序）
     * @param userId
     * @return
     */
    public Map<String,Object> selectUserData(Long userId){
        return this.webUserCardRechargeMapper.selectUserData(userId);
    }
    @Autowired
    private IWebUserCardRechargeLogService iWebUserCardRechargeLogService;
    @Autowired
    private IWebUserCardTimeService iWebUserCardTimeService;
    @Autowired
    private IWebUserCardRechargeTransitionService iWebUserCardRechargeTransitionService;
    @Autowired
    private IWebDeptProductService iWebDeptProductService;
    @Autowired
    private IWebDeptProductLogService iWebDeptProductLogService;
    @Autowired
    private IWebUserService iWebUserService;
    @Autowired
    private ISysDeptService iSysDeptService;
}
